/**
 * 右键菜单组件
 */

import { useState, useEffect, useRef } from 'react'
import type { PluginComponentProps } from '../../types'
import { deleteShift } from '../../api'
import { toast } from '../../utils/toast'
import './styles.css'

interface MenuPosition {
  x: number
  y: number
}

export function ContextMenu({ context }: PluginComponentProps) {
  const [isVisible, setIsVisible] = useState(false)
  const [position, setPosition] = useState<MenuPosition>({ x: 0, y: 0 })
  const [targetCell, setTargetCell] = useState<{
    employeeId: string | number
    date: string
  } | null>(null)
  const menuRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    // 监听右键菜单事件
    const unsubContextMenu = context.on(
      'cell:contextMenu',
      (data: { employeeId: string | number; date: string; x: number; y: number }) => {
        setPosition({ x: data.x, y: data.y })
        setTargetCell({ employeeId: data.employeeId, date: data.date })
        setIsVisible(true)
      }
    )

    // 点击其他地方关闭菜单
    const handleClickOutside = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setIsVisible(false)
      }
    }

    document.addEventListener('click', handleClickOutside)

    return () => {
      unsubContextMenu()
      document.removeEventListener('click', handleClickOutside)
    }
  }, [context])

  if (!isVisible || !targetCell) return null

  const handleAddShift = () => {
    // 触发添加班次，并传递默认值
    context.emit('cell:click', {
      employeeId: targetCell.employeeId,
      date: targetCell.date,
    })
    setIsVisible(false)
  }

  const handleEditShift = () => {
    // 查找该位置的班次（使用 == 处理类型不匹配）
    const shift = context
      .getShifts()
      .find(s => s.employeeId == targetCell.employeeId && s.date === targetCell.date)

    if (shift) {
      context.emit('shift:click', shift)
    }
    setIsVisible(false)
  }

  const handleDeleteShift = async () => {
    // 查找该位置的班次并删除（使用 == 处理类型不匹配）
    const shift = context
      .getShifts()
      .find(s => s.employeeId == targetCell.employeeId && s.date === targetCell.date)

    if (!shift) {
      setIsVisible(false)
      return
    }

    setIsVisible(false)

    toast.confirm({
      title: '确认删除',
      message: '确定要删除这个班次吗？此操作无法撤销。',
      confirmText: '删除',
      cancelText: '取消',
      onConfirm: async () => {
        try {
          console.log('🗑️ 从右键菜单删除班次:', shift.id)

          // 先调用 API 删除
          await deleteShift(shift.id)

          // 然后从本地状态删除
          context.removeShift(shift.id)
          console.log('✅ 班次删除成功')

          // 通知外部刷新数据
          if ((window as any).refreshScheduleData) {
            setTimeout(() => (window as any).refreshScheduleData(), 100)
          }

          toast.success('班次删除成功')
        } catch (error) {
          console.error('❌ 删除班次失败:', error)
          toast.error('删除失败，请检查服务器是否正常运行')
        }
      },
    })
  }

  // 检查该位置是否有班次（使用 == 处理类型不匹配）
  const hasShift = context
    .getShifts()
    .some(s => s.employeeId == targetCell.employeeId && s.date === targetCell.date)

  return (
    <div
      ref={menuRef}
      className="context-menu"
      style={{
        left: `${position.x}px`,
        top: `${position.y}px`,
      }}
    >
      {!hasShift ? (
        <div className="context-menu-item" onClick={handleAddShift}>
          <span className="context-menu-icon">➕</span>
          <span>添加班次</span>
        </div>
      ) : (
        <>
          <div className="context-menu-item" onClick={handleEditShift}>
            <span className="context-menu-icon">✏️</span>
            <span>编辑班次</span>
          </div>
          <div className="context-menu-divider" />
          <div className="context-menu-item context-menu-item-danger" onClick={handleDeleteShift}>
            <span className="context-menu-icon">🗑️</span>
            <span>删除班次</span>
          </div>
        </>
      )}
    </div>
  )
}
